<?php

namespace App\Customer\Model;


use App\Customer\Model\ResumeRecommend as RecommendModel;
use App\Facades\UrlCrypt;
use App\Service\DbIndex;
use App\Service\EsSearch;
use App\Web\Model\CaseFlow;
use App\Web\Model\Manager;
use App\Web\Model\Resume as ResumeModel;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Redis;
use Exception;
use RuntimeException;

class CaseResumeModel extends Model {

    /**
     * 获取职位下的简历数据
     * @param array $searchParam
     * @param int $pageNum
     * @param int $pageLimit
     * @return array
     */
    public function getCaseResumeInfo(array $searchParams, $pageNum = 1, $pageLimit = 10): array {
        list($pageNum, $rowFrom, $rowTo) = $this->paginationParameters($pageNum, $pageLimit);
        //格式化返回数组
        $resultBody = [
            'status' => true,
            'message' => '获取成功',
            'totalCount' => 0,
            'pagenum' => $pageNum,
            'engine' => true,
            'keycodes' => '',
            'costLog' => '',
            'listkey' => '',
            'listtoken' => '',
            'eserror' => '',
            'resumelist' => []
        ];

        $caseResumeKeycodes = '';
        //有keycodes，直接分页
        if (isset($searchParams['keycodes']) && !empty($searchParams['keycodes'])) {
            $searchCaseResumeKeycodes = explode(',', $searchParams['keycodes']);
            $resultBody['totalCount'] = 0;
            $resultBody['engine'] = false;
            //超出最多查询50条
            $caseResumeKeycodes = implode(',', array_slice($searchCaseResumeKeycodes, 0, 50));
            //有简历id直接查询数据库
        } else {
            if (!empty($searchParams['caseid'])) {
                $esServer = EsSearch::getInstance();
                //设置隐藏字段
                $unShowFlowat = $this->getUnShowFloat(1);
                $search = [
                    EsSearch::EQUAL => $searchParams,
                    EsSearch::NOTEQUAL => $unShowFlowat
                ];
                $searchCaseResumeKeycodesData = $esServer->setIndex(EsSearch::ES_INDEX_CASE_EN_RESUME)
                    ->setFields('keycode')
                    ->setWhere($search)->search();

                if ($searchCaseResumeKeycodesData['eserror'] === 1) {
                    $resultBody['eserror'] = 1;
                    return $resultBody;
                }
                if (!empty($searchCaseResumeKeycodesData['data'])) {
                    $searchCaseResumeKeycodes = array_column($searchCaseResumeKeycodesData['data'], 'keycode');
                    $resultBody['totalCount'] = count($searchCaseResumeKeycodes);
                    $caseResumeKeycodes = implode(',', array_slice($searchCaseResumeKeycodes, $rowFrom, ($rowTo - $rowFrom)));
                    $resultBody['keycodes'] = implode(',', $searchCaseResumeKeycodes);
                }
            }
        }
        if (!empty($caseResumeKeycodes)) {
            $searchParams['caseresumekeycode'] = $caseResumeKeycodes;
            $resultBody['resumelist'] = $this->getCaseResumeList($searchParams, 0, 1000);
        }

        $resumeidArr = array_column($resultBody['resumelist'], 'resumeid');
        $resultBody['listkey'] = implode(",", $resumeidArr);
        $resultBody['listtoken'] = UrlCrypt::generateToken($resumeidArr);
        return $resultBody;
    }

    /**
     * Notes:获取职位下简历列表
     * @param $oprId
     * @param $subId
     * @param $projectId
     * @param array $searchParams
     * @param int $rowFrom
     * @param int $rowTo
     * @return array
     * @throws Exception
     */
    public function getCaseResumeList(array $searchParams = [], $rowFrom = 0, $rowTo = 0) {
        $resumeList = $this->getCaseResumeSearch($searchParams, false, $rowFrom, $rowTo);
        $resumeIds = array_column($resumeList, 'resumeid');
        $resumeInfos = $this->getResumeList($resumeIds, $searchParams['subid']);
        //翻译一级二级流程
        $caseFlowModel = new CaseFlow();
        $resumeList = $caseFlowModel->rowTrans($resumeList);

        foreach ($resumeList as $key => &$item) {
            if (isset($resumeInfos[$item['resumeid']])) {
                $resumeList[$key]['resumeinfo'] = $resumeInfos[$item['resumeid']];
            }
            $item['timecontrol'] = isset($item['timecontrol']) && !empty($item['timecontrol']) ? date("Y-m-d H:i", strtotime($item['timecontrol'])) : '';
            $item['tagadddate'] = isset($item['tagadddate']) && !empty($item['tagadddate']) ? date("Y-m-d H:i", strtotime($item['tagadddate'])) : '';
            $item['updatedate'] = isset($item['updatedate']) && !empty($item['updatedate']) ? date("Y-m-d H:i", strtotime($item['updatedate'])) : '';
            $item['createdate'] = isset($item['createdate']) && !empty($item['createdate']) ? date("Y-m-d H:i", strtotime($item['createdate'])) : '';
        }
        return $resumeList;
    }

    /**
     * 获取简历列表
     * @param $resumeIds
     * @param $oprId
     * @return array
     */
    public function getResumeList($resumeIds, $subId) {
        $resumeInfoList = $resumeInfos = [];
        if (!empty($resumeIds)) {
            $managerModel = new Manager();
            $fields = 'cname,managerid,userid51job as resumeid,relationaccid as accountid,birthday,gender,area,funtype,workindustry,
            degree,lastupdate,expsalaryfrom,expsalaryto,major,school,company,division,position,workyear,email,mobilephone,
            case when profile is null then 0 else 1 end as isprofile,expectarea,currsalaryfrom,currsalaryto';
            $resumeInfoList = $managerModel->getManagerListByResumeId($resumeIds, $fields);
            $recommendModel = new RecommendModel();
            foreach ($resumeInfoList as $resumeInfo) {
                //生成简历链接
                $keyVerify = [];
                $keyVerify['recommendid'] = '';
                $keyVerify['subid'] = $subId;
                $resumeInfo['token'] = UrlCrypt::generateToken($keyVerify);
                $resumeInfo['url'] = $recommendModel->creatRecommendResumeUrl($subId, $resumeInfo['resumeid'], $resumeInfo['token']);
                $resumeInfos[$resumeInfo['resumeid']] = $resumeInfo;
            }
            $resumeModel = new ResumeModel();
            $showFields = ['cname' => 1,'company' => 1];
            $resumeModel->hideFields($resumeInfos, $showFields);
        }

        return $resumeInfos;
    }

    /**
     * 获取职位中简历
     * @param $oprId
     * @param $subId
     * @param array $searchParams
     * @param bool $searchCount
     * @param int $rowFrom
     * @param int $rowTo
     * @param string $orderBy
     * @return array
     * @throws Exception
     */
    protected function getCaseResumeSearch(array $searchParams = [], $searchCount = true, $rowFrom = 0, $rowTo = 0) {
        if (!isset($searchParams['mode'])) {
            $searchParams['mode'] = '';
        }
        //获取当前登录用户能操作的职位信息
        $searchCaseIds = empty($searchParams['caseid']) ? [] : array_filter(explode(',', $searchParams['caseid']));
        $searchCaseStatus = isset($searchParams['casestatus']) && $searchParams['casestatus'] == 'active' ? 'active' : 'all';
        $caseModel = new CaseModel();
        $caseList = $caseModel->getCaseListWithProjectId('caseid,casename,status as casestatus', $searchCaseStatus, $searchCaseIds);
        $caseIds = [];
        $caseInfoList = [];
        foreach ($caseList as $caseInfo) {
            $caseIds[] = $caseInfo['caseid'];
            $caseInfoList[$caseInfo['caseid']] = $caseInfo;
        }
        unset($caseList);
        if (empty($caseIds)) {
            return [];
        }
        $subId = $searchParams['subid'];
        $dbIndex = DbIndex::getDbIndex($subId);
        $dbName = 'jyrpo_' . $dbIndex['dbid'];
        $searchCaseResumeKeycodes = empty($searchParams['caseresumekeycode']) ? [] : array_filter(explode(',', $searchParams['caseresumekeycode']));
        /////////////////////////////////////////////////////////////////////////////
        $where = [];
        $var = [];
        //根据caseresume表keycode查询
        if (!empty($searchCaseResumeKeycodes) && is_array($searchCaseResumeKeycodes)) {
            $where[] = 'keycode IN(' . substr(str_repeat('?,', count($searchCaseResumeKeycodes)), 0, -1) . ')';
            $var = array_merge($var, $searchCaseResumeKeycodes);
        }

        $field = $searchCount ? 'count(1) as count' : null;
        $field = $field ?? 'id,resumeid,caseid,projectid,subid,flowat,flowatstatus,timecontrol,createdate,updator,updatedate,tagadderid,tagaddername,tagadddate,keycode,taghisid,salary';

        if ($searchParams['mode'] == 'ElasticeSearch') {
            $field = 'id,resumeid';
        }

        $caseIdInFlags = substr(str_repeat('?,', count($caseIds)), 0, -1);
        $sql = 'SELECT ' . $field . ' FROM CaseResume_' . $dbIndex['tableid'] . ' WHERE subid=? AND status=? AND caseid IN(' . $caseIdInFlags . ')';
        if (!empty($where)) {
            $sql .= ' AND ' . implode(' AND ', $where);
        }
        $orderBy = $searchCount ? '' : 'createdate DESC,id DESC';
        if (!empty($orderBy)) {
            $sql .= ' ORDER BY ' . $orderBy;
        }
        $var = array_merge([$subId, '01',], $caseIds, $var);
        $result = Db::connect($dbName)->select($sql, $var, $rowFrom, $rowTo);
        if ($searchCount) {
            return $result;
        }

        if ($searchParams['mode'] != 'ElasticeSearch') {
            for ($i = 0; $i < count($result); $i++) {
                $result[$i]['casename'] = $caseInfoList[$result[$i]['caseid']]['casename'];
                $result[$i]['casestatus'] = $caseInfoList[$result[$i]['caseid']]['casestatus'];
            }
        }
        return $result;
    }

    /**
     * @param $type 1.返回 1 2级流程组合 2.返回1 2级数组关联关系
     * @return array
     */
    public function getUnShowFloat($type) {
        try {
            //获取隐藏字段
            $unShowFlowList = config('app.customer_unshow_caseflow');
            if (!is_file($unShowFlowList)) {
                throw new RuntimeException('隐藏流程未定义');
            }
            $flowList = include $unShowFlowList;
            $list = [];
            switch ($type) {
                case 1:
                    $list = [
                        'flowat_flowatstatus' => []
                    ];
                    if (!empty($flowList)) {
                        foreach ($flowList as $flowat => $value) {
                            if (isset($value['child']) && !empty($value['child'])) {
                                foreach ($value['child'] as $flowatStatus => $item) {
                                    $list['flowat_flowatstatus'][] = $flowat . $flowatStatus;
                                }
                            } else {
                                //获取二级流程下的节点
                                $caseFlowList = config('app.global_caseflow');
                                if (!is_file($caseFlowList)) {
                                    throw new RuntimeException('职位流程未定义');
                                }
                                $caseFlow = include $caseFlowList;
                                $child = $caseFlow[$flowat]["child"];
                                if (!empty($child)) {
                                    foreach ($child as $status => $item) {
                                        $list['flowat_flowatstatus'][] = $flowat . $status;
                                    }
                                }
                            }
                        }
                    }
                    break;
                case 2:
                    $list = $flowList;
                    break;
            }
            return $list;

        } catch (Exception $exception) {

            return [];
        }
    }
}